import Http from 'axios';
import { message } from 'antd';
import { history } from 'umi';

const ajax = <T = any>(url: string, params: any = {}) => {
  params.url = url;
  return new Promise<T>((resolve, reject) => {
    Http(params)
      .then((res: any) => {
        if (+res.data.code === 0) {
          resolve(res.data.data);
        } else if (+res.data.code === 999) {
          localStorage.setItem('token', '');
          localStorage.setItem('username', '');
          message.error(`${res.data.msg}`);
          reject(res.data.msg);
          setTimeout(() => {
            history.push('/login');
          }, 1200);
        } else {
          message.error(`${res.data.msg}`);
          reject(res.data.msg);
        }
      })
      .catch((err: any) => {
        message.error(`${err}`);
        reject(`${err}`);
      });
  });
};

export default {
  request(baseURL: string) {
    let host = baseURL;
    return function<T = any>(params: any) {
      const id_token = localStorage.getItem('token');
      // 获取token_id
      params.opts = params.opts || {};
      let apiParams = {};
      Http.defaults.withCredentials = true;
      if (params.method === 'get') {
        // 防止页面不刷新
        let t = new Date().getTime();
        apiParams = {
          headers: {
            token: id_token,
          },
          params: { ...params.opts, t },
          method: params.method,
        };
      } else if (params.method === 'post') {
        apiParams = {
          headers: {
            token: id_token,
            'content-type': 'application/json',
          },
          data: params.opts,
          method: params.method,
        };
      }
      // apiParams = {
      //   headers: {
      //     token: id_token,
      //     'content-type': 'application/json',
      //   },
      //   data: params.opts,
      //   method: params.method,
      // };
      // 可以做一些token之类的操作
      return ajax<T>(host + params.url, apiParams);
    };
  },
};
